package cn.tedu.qxhouserent.passport.service.impl;


import cn.tedu.qxhouserent.commons.ex.ServiceException;
import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.commons.util.PageInfoToPageDataConverter;
import cn.tedu.qxhouserent.commons.web.ServiceCode;
import cn.tedu.qxhouserent.passport.mapper.*;
import cn.tedu.qxhouserent.passport.pojo.entity.AdminRole;
import cn.tedu.qxhouserent.passport.pojo.entity.Role;
import cn.tedu.qxhouserent.passport.pojo.entity.RolePermission;
import cn.tedu.qxhouserent.passport.pojo.param.RoleAddNewParam;
import cn.tedu.qxhouserent.passport.pojo.param.RoleUpdateInfoParam;
import cn.tedu.qxhouserent.passport.pojo.vo.RoleListItemVO;
import cn.tedu.qxhouserent.passport.pojo.vo.RoleStandardVO;
import cn.tedu.qxhouserent.passport.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

import static cn.tedu.qxhouserent.commons.web.ServiceCode.ERR_DELETE;

import static cn.tedu.qxhouserent.commons.web.ServiceCode.ERR_INSERT;

@Service
@Slf4j


public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    AdminRoleMapper adminRoleMapper;
    @Autowired
    RolePermissionMapper rolePermissionMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    AdminMapper adminMapper;


    public void addNew(RoleAddNewParam roleAddNewParam){
        log.debug("开始处理【添加角色】的业务，参数：{}" ,roleAddNewParam);
        //判断角色名称是否已经被占用
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",roleAddNewParam.getName());
        int countByName = roleMapper.selectCount(queryWrapper);
        log.debug("根据角色名称统计匹配的角色数量，结果：{}" , countByName);
        if (countByName>0){
            String message = "添加角色失败,角色名称已被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //向角色表中添加数据
        log.debug("向角色表中添加数据");
        Role role = new Role();
        BeanUtils.copyProperties(roleAddNewParam,role);
        role.setGmtCreate(LocalDateTime.now());
        role.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的角色数据写入到数据库，数据：{}" , role);
        int insert = roleMapper.insert(role);
        if (insert != 1) {
            String message = "添加失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("向角色表中添加数据，完成！");

        //向admin_role表中添加数据
//        log.debug("向admin_role表中添加数据");
//        Long[] adminIds = roleAddNewParam.getAdminIds();
//        if (adminIds.length != 0) {
//            AdminRole[] adminRoles = new AdminRole[adminIds.length];
//            for (int i = 0; i < adminRoles.length; i++) {
//                AdminRole adminRole = new AdminRole();
//                adminRole.setAdminId(adminIds[i])
//                        .setRoleId(role.getId())
//                        .setGmtCreate(LocalDateTime.now())
//                        .setGmtModified(LocalDateTime.now());
//                adminRoles[i] = adminRole;
//            }
//            int i = adminRoleMapper.insertBatch(adminRoles);
//            if (i != adminIds.length) {
//                String message = "添加失败，服务器忙，请稍后再试！";
//                log.warn(message);
//                throw new ServiceException(ServiceCode.ERR_INSERT, message);
//            }
//        }
//        log.debug("向admin_role表中添加数据，完成！");

        //向role_permission表中添加数据
        log.debug("向role_permission表中添加数据");
        Long[] permissionIds = roleAddNewParam.getPermissionIds();
        if (permissionIds.length != 0) {
            RolePermission[] rolePermissions = new RolePermission[permissionIds.length];
            for (int i = 0; i < permissionIds.length; i++) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(role.getId())
                        .setPermissionId(permissionIds[i])
                        .setGmtCreate(LocalDateTime.now())
                        .setGmtModified(LocalDateTime.now());
                rolePermissions[i] = rolePermission;
            }
            int i = rolePermissionMapper.insertBatch(rolePermissions);
            if (i != permissionIds.length) {
                String message = "添加失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_INSERT, message);
            }
        }
        log.debug("向role_permission表中添加数据，完成！");

        log.debug("处理【添加角色】业务，完成！");
    }

    @Override
    public PageData<RoleListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public void deleteById(Long roleId) {
        log.debug("开始处理【通过id删除角色】的业务，参数：{}" ,roleId);
        //判断是否有此角色
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",roleId);
        int countByName = roleMapper.selectCount(queryWrapper);
        log.debug("根据角色id统计匹配的角色数量，结果：{}" , countByName);
        if (countByName==0){
            String message = "删除角色失败，角色数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //开始删除角色
        int i = roleMapper.deleteById(roleId);
        if (i != 1) {
            String message = "删除失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }

        //将原有admin_role关联删除
        QueryWrapper<AdminRole> adminRoleQueryWrapper = new QueryWrapper<>();
        adminRoleQueryWrapper.eq("role_id", roleId);
        Integer integer = adminRoleMapper.selectCount(adminRoleQueryWrapper);

        if (integer != 0) {
            int i1 = adminRoleMapper.deleteByRoleId(roleId);
            if (i1 != integer) {
                String message = "删除失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_DELETE, message);
            }
        }

        //将原有role_permission关联删除
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("role_id", roleId);
        Integer integer1 = rolePermissionMapper.selectCount(rolePermissionQueryWrapper);

        if (integer1 != 0) {
            int i1 = rolePermissionMapper.deleteByRoleId(roleId);
            if (i1 != integer1) {
                String message = "删除失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_DELETE, message);
            }
        }

        log.debug("通过id删除角色数据，完成！");
    }


    @Override
    public void updateInfoById(Long roleId, RoleUpdateInfoParam roleUpdateInfoParam) {
        log.debug("开始处理【修改角色详情】的业务，ID：{}, 新数据：{}", roleId, roleUpdateInfoParam);
        // 检查角色是否存在，如果不存在，则抛出异常
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", roleId);
        int countById = roleMapper.selectCount(queryWrapper);
        log.debug("根据角色ID统计匹配的角色数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改角色详情失败，角色数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查角色名称是否被其它角色占用，如果被占用，则抛出异常
        QueryWrapper<Role> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("name", roleUpdateInfoParam.getName())
                .ne("id", roleId);
        int countByName = roleMapper.selectCount(queryWrapper2);
        log.debug("根据角色名称统计匹配的角色数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改角色详情失败，角色名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行对角色表的修改
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateInfoParam, role);
        role.setId(roleId);
        int i2 = roleMapper.updateById(role);
        if (i2 != 1) {
            String message = "更新失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的角色数据更新入到角色表中，完成！");

        //将原有role_permission关联删除
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("role_id", roleId);
        Integer integer = rolePermissionMapper.selectCount(rolePermissionQueryWrapper);

        if (integer != 0) {
            int i1 = rolePermissionMapper.deleteByRoleId(roleId);
            if (i1 != integer) {
                String message = "删除失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_DELETE, message);
            }
        }

        //新增role_permission新关联
        Long[] permissionIds = roleUpdateInfoParam.getPermissionIds();
        if (permissionIds.length != 0) {
            RolePermission[] rolePermissions = new RolePermission[permissionIds.length];
            for (int j = 0; j < permissionIds.length; j++) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setPermissionId(permissionIds[j])
                        .setRoleId(roleId)
                        .setGmtCreate(LocalDateTime.now())
                        .setGmtModified(LocalDateTime.now());
                rolePermissions[j] = rolePermission;
            }
            int i3 = rolePermissionMapper.insertBatch(rolePermissions);
            if (i3 != rolePermissions.length) {
                String message = "添加失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ERR_INSERT, message);
            }
        }

        //将原有admin_role关联删除
//        QueryWrapper<AdminRole> rolePermissionQueryWrapper1 = new QueryWrapper<>();
//        rolePermissionQueryWrapper1.eq("role_id", roleId);
//        Integer integer1 = adminRoleMapper.selectCount(rolePermissionQueryWrapper1);
//
//        if (integer1 != 0) {
//            int i1 = adminRoleMapper.deleteByRoleId(roleId);
//            if (i1 != integer1) {
//                String message = "删除失败，服务器忙，请稍后再试！";
//                log.warn(message);
//                throw new ServiceException(ERR_DELETE, message);
//            }
//        }

        //新增admin_role新关联
//        Long[] adminIds = roleUpdateInfoParam.getAdminIds();
//        if (adminIds.length != 0) {
//            AdminRole[] adminRoles = new AdminRole[adminIds.length];
//            for (int j = 0; j < adminIds.length; j++) {
//                AdminRole adminRole = new AdminRole();
//                adminRole.setAdminId(adminIds[j])
//                        .setRoleId(roleId)
//                        .setGmtCreate(LocalDateTime.now())
//                        .setGmtModified(LocalDateTime.now());
//                adminRoles[j] = adminRole;
//            }
//            int i3 = adminRoleMapper.insertBatch(adminRoles);
//            if (i3 != adminRoles.length) {
//                String message = "添加失败，服务器忙，请稍后再试！";
//                log.warn(message);
//                throw new ServiceException(ERR_INSERT, message);
//            }
//        }
    }

    @Override
    public PageData<RoleListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询角色列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<RoleListItemVO> list = roleMapper.list();
        PageInfo<RoleListItemVO> pageInfo = new PageInfo<>(list);
        PageData<RoleListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public RoleStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询角色详情】的业务，参数：{}", id);
        RoleStandardVO queryResult = roleMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询角色详情失败，角色数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }
}
